/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.co.cyberagent.stf;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.os.Bundle;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;

import android.content.res.Configuration;

public class App extends Activity {
    private int width = 1280;
    private int height = 720;
    private int rotation = 0;
    private boolean flag = true;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        TextView tv = new TextView(this);
        // Toast.LENGTH_LONG).show();
        // System.loadLibrary("miniserver");
        // System.loadLibrary("backtrace");
        // System.loadLibrary("base");
        // System.loadLibrary("binder");
        // System.loadLibrary("c++");
        // System.load("libminiserver.so");
        System.loadLibrary("miniserver");

        // startInShell("");
        Button btn_fake = new Button(this);
        btn_fake.setText("Fake");
        btn_fake.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        btn_fake.setLayoutParams(new LinearLayout.LayoutParams(10, 100));
        btn_fake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                byte[] resutl = MiniLib.get_cap(80);
                if (resutl != null) {
                    Toast.makeText(getApplicationContext(), "size: " + resutl.length, Toast.LENGTH_LONG).show();
                    try {

                        FileOutputStream outputStream = openFileOutput("aaa.jpg", Activity.MODE_PRIVATE);
                        outputStream.write(resutl);
                        outputStream.flush();
                        outputStream.close();
                        Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_LONG).show();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        // here, we dynamically load the library at runtime
        // before calling the native method.
        //

        // tv.setText( "The sum of " + x + " and " + y + " is ");
        // setContentView(tv);
        // setContentView(btn_fake);
        // byte[] aaa = new byte[0x50000];
        int ret = init_cap(720, 1280, 720, 1280, 0);
        if (ret == 0) {
            Toast.makeText(getApplicationContext(), "init minicap OK", Toast.LENGTH_LONG).show();
            // return ;
        } else {
            tv.setText("error init_cap");
            Toast.makeText(getApplicationContext(), "init minicap error", Toast.LENGTH_LONG).show();
        }

        // get_banner(aaa);
        // byte[] resutl = get_cap(aaa, 80);
        // if (resutl != null)
        // {
        // tv.setText(aaa.toString()+ "size: "+ resutl.length);
        // }

        release_cap();
        ret = init_cap(720, 1280, 720, 1280, 0);
        if (ret == 0) {
            Toast.makeText(getApplicationContext(), "init minicap OK", Toast.LENGTH_LONG).show();
            // return ;
        } else {
            tv.setText("error init_cap");
            Toast.makeText(getApplicationContext(), "init minicap error", Toast.LENGTH_LONG).show();
            return;
        }

        release_cap();

        if (init_touch() == 0) {
            Toast.makeText(getApplicationContext(), "init touch ok", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "init touch error", Toast.LENGTH_LONG).show();
            return;
        }

        free_touch();
        if (reset_touch() == 0) {
            Toast.makeText(getApplicationContext(), "init touch ok", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "init touch error", Toast.LENGTH_LONG).show();
            return;
        }

        // set_rotation(720, 1280, 720, 1280, 90);

        ret = init_cap(720, 1280, 720, 1280, 0);
        if (ret == 0) {
            Toast.makeText(getApplicationContext(), "init minicap OK", Toast.LENGTH_LONG).show();
        } else {
            tv.setText("error init_cap");
            Toast.makeText(getApplicationContext(), "init minicap error", Toast.LENGTH_LONG).show();
            return ;
        }

        new Thread(new Runnable() {
            @SuppressLint("LongLogTag")
            @Override
            public void run() {
                while (true) {

                    // byte[] resutl = get_screen(width, height, width, height, rotation, 80);
                    // if (resutl == null || resutl.length <= 0) {
                    // continue;
                    // }
                    // String str = byte2hex(resutl);
                    // Log.d("Maing----->get_screen", str);
                    // continue;
                    try {
                        Thread.sleep(30);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (!flag) {
                        Log.d("MaingC----->set_rotation:p:" + android.os.Process.myPid() + " t:"
                                + android.os.Process.myTid(),
                                width + "x" + height + "@" + width + "x" + height + "/" + rotation);
                        set_rotation(width, height, width, height, rotation);
                        flag = true;
                    }

                    byte[] resutl1 = get_cap(80);
                    if (resutl1 == null || resutl1.length <= 0) {
                        continue;
                    }
                    String str1 = byte2hex(resutl1);
                    Log.d("MaingC----->get_cap:p:" + android.os.Process.myPid() + " t:" + android.os.Process.myTid(),
                            str1);
                }
            }
        }).start();

         new Thread(new Runnable() {
             @SuppressLint("LongLogTag")
             @Override
             public void run() {
                 while (true) {

                     // byte[] resutl = get_screen(width, height, width, height, rotation, 80);
                     // if (resutl == null || resutl.length <= 0) {
                     // continue;
                     // }
                     // String str = byte2hex(resutl);
                     // Log.d("Maing----->get_screen", str);
                     // continue;
                     try {
                         Thread.sleep(30);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }

                     if (!flag) {
                         set_rotation(width, height, width, height, rotation);
                         flag = true;
                     }

                     byte[] resutl1 = get_cap(80);
                     if (resutl1 == null || resutl1.length <= 0) {
                         continue;
                     }
                     String str1 = byte2hex(resutl1);
                     Log.d("MaingC----->get_cap:p:" + android.os.Process.myPid() + " t:" + android.os.Process.myTid(),
                             str1);
                 }
             }
         }).start();

        // new Thread(new Runnable() {
        // @Override
        // public void run() {
        // while (true) {
        //
        // byte[] resutl = get_screen(width, height, width, height, rotation, 80);
        // if (resutl == null || resutl.length <= 0) {
        // continue;
        // }
        // String str = byte2hex(resutl);
        // Log.d("Maing----->get_screen", str);
        // // continue;
        // try {
        // Thread.sleep(20);
        // } catch (InterruptedException e) {
        // e.printStackTrace();
        // }
        //
        // if (!flag) {
        // set_rotation(width, height, width, height, rotation);
        // flag = true;
        // }
        //
        // byte[] resutl1 = get_cap(80);
        // if (resutl1 == null || resutl1.length <= 0) {
        // continue;
        // }
        // String str1 = byte2hex(resutl1);
        // Log.d("MaingC----->get_cap:p:" + android.os.Process.myPid() + " t:" +
        // android.os.Process.myTid(), str1);
        // }
        // }
        // }).start();
    }

    private static String byte2hex(byte[] buffer) {
        String h = "";
        // Log.d("Maing", "length: " + buffer.length);
        for (int i = 0; i < 100; i++) {
            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            h = h + " " + temp;
        }

        return h;
    }

    public void fakeClickHandler(View v) {
        byte[] resutl = MiniLib.get_cap(80);
        if (resutl != null) {
            Toast.makeText(getApplicationContext(), "size: " + resutl.length, Toast.LENGTH_LONG).show();
            try {
            
                FileOutputStream outputStream = openFileOutput("aaa.jpg", Activity.MODE_PRIVATE);
                outputStream.write(resutl);
                outputStream.flush();
                outputStream.close();
                Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_LONG).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public void testClickHandler(View v) {
        Toast.makeText(getApplicationContext(), "hello coco", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // release_cap();
    }

    // @Override
    // public void onConfigurationChanged(Configuration newConfig) {
    //     super.onConfigurationChanged(newConfig);
    //     // newConfig.orientation获得当前屏幕状态是横向或者竖向
    //     // Configuration.ORIENTATION_PORTRAIT 表示竖向
    //     // Configuration.ORIENTATION_LANDSCAPE 表示横屏
    //     if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
    //         Toast.makeText(this, "现在是竖屏", Toast.LENGTH_SHORT).show();
    //     }
    //     if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    //         Toast.makeText(this, "现在是横屏", Toast.LENGTH_SHORT).show();
    //     }
    // }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // newConfig.orientation获得当前屏幕状态是横向或者竖向
        // Configuration.ORIENTATION_PORTRAIT 表示竖向
        // Configuration.ORIENTATION_LANDSCAPE 表示横屏
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

            flag = false;
            int realWidth = 0, realHeight = 0;
            try {
                Display display = this.getWindowManager().getDefaultDisplay();
                DisplayMetrics metrics = new DisplayMetrics();
                display.getMetrics(metrics);
                if (android.os.Build.VERSION.SDK_INT >= 17) {
                    Point size = new Point();
                    display.getRealSize(size);
                    realWidth = size.x;
                    realHeight = size.y;
                } else if (android.os.Build.VERSION.SDK_INT < 17 && android.os.Build.VERSION.SDK_INT >= 14) {
                    Method mGetRawH = Display.class.getMethod("getRawHeight");
                    Method mGetRawW = Display.class.getMethod("getRawWidth");
                    realWidth = (Integer) mGetRawW.invoke(display);
                    realHeight = (Integer) mGetRawH.invoke(display);
                } else {
                    realWidth = metrics.widthPixels;
                    realHeight = metrics.heightPixels;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            int Rotation = 0;
            int angle = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
            switch (angle) {
            case Surface.ROTATION_0:
                Rotation = 0;
                break;
            case Surface.ROTATION_90:
                Rotation = 90;
                break;
            case Surface.ROTATION_180:
                Rotation = 180;
                break;
            case Surface.ROTATION_270:
                Rotation = 270;
                break;
            default:
                Log.d("Maing", "onConfigurationChanged----------------------> Default Rotation!");
                break;
            }

            rotation = Rotation;
            width = realWidth;
            height = realHeight;
            Toast.makeText(App.this, "现在是竖屏", Toast.LENGTH_SHORT).show();
            Log.e("Maing",
                    "onConfigurationChanged----------------------> " + realWidth + "x" + realHeight + "/" + Rotation);
        }
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

            flag = false;
            int realWidth = 0, realHeight = 0;
            try {
                Display display = this.getWindowManager().getDefaultDisplay();
                DisplayMetrics metrics = new DisplayMetrics();
                display.getMetrics(metrics);
                if (android.os.Build.VERSION.SDK_INT >= 17) {
                    Point size = new Point();
                    display.getRealSize(size);
                    realWidth = size.x;
                    realHeight = size.y;
                } else if (android.os.Build.VERSION.SDK_INT < 17 && android.os.Build.VERSION.SDK_INT >= 14) {
                    Method mGetRawH = Display.class.getMethod("getRawHeight");
                    Method mGetRawW = Display.class.getMethod("getRawWidth");
                    realWidth = (Integer) mGetRawW.invoke(display);
                    realHeight = (Integer) mGetRawH.invoke(display);
                } else {
                    realWidth = metrics.widthPixels;
                    realHeight = metrics.heightPixels;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            int Rotation = 0;
            int angle = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
            switch (angle) {
            case Surface.ROTATION_0:
                Rotation = 0;
                break;
            case Surface.ROTATION_90:
                Rotation = 90;
                break;
            case Surface.ROTATION_180:
                Rotation = 180;
                break;
            case Surface.ROTATION_270:
                Rotation = 270;
                break;
            default:
                Log.d("Maing", "----------------------> Default Rotation!");
                break;
            }

            rotation = Rotation;
            width = realWidth;
            height = realHeight;
            Toast.makeText(App.this, "现在是横屏", Toast.LENGTH_SHORT).show();
            Log.d("Maing",
                    "onConfigurationChanged----------------------> " + realWidth + "x" + realHeight + "/" + Rotation);
        }
    }

    void startInShell(String str) {
        String str2 = "app_process";
        if (new File("/system/bin/app_process32").exists()) {
            str2 = "app_process32";
        }
        try {
            Log.d("Maing", "---start app_process---");
            DataOutputStream dataOutputStream = new DataOutputStream(Runtime.getRuntime().exec("su").getOutputStream());
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("export CLASSPATH=");
            stringBuilder.append(this.getApplicationInfo().sourceDir);
            // stringBuilder.append("echo -4 > /proc/"+
            // android.os.Process.myPid()+"/oom_adj");
            stringBuilder.append(" \n");
            // stringBuilder.append("/foo.jar\n");
            // stringBuilder.append("com.example.helloworld\n");
            Log.d("Maing", "---------------------" + "exec: " + stringBuilder.toString());
            dataOutputStream.writeBytes(stringBuilder.toString());
            dataOutputStream.flush();
            Display defaultDisplay = ((WindowManager) this.getSystemService("window")).getDefaultDisplay();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            defaultDisplay.getRealMetrics(displayMetrics);
            stringBuilder = new StringBuilder();
            stringBuilder.append("exec ");
            stringBuilder.append(str2);
            stringBuilder.append(" ");
            // stringBuilder.append("-Djava.library.path=");
            // stringBuilder.append(this.getApplicationInfo().nativeLibraryDir);
            // stringBuilder.append(" ");
            // stringBuilder.append(this.getPackageName());
            stringBuilder.append("/system/bin");
            stringBuilder.append(" ");
            stringBuilder.append("jp.co.cyberagent.stf.MiniLib");
            // stringBuilder.append(" ");
            // stringBuilder.append(str);
            // stringBuilder.append(" ");
            // stringBuilder.append(displayMetrics.widthPixels);
            // stringBuilder.append(" ");
            // stringBuilder.append(displayMetrics.heightPixels);
            // stringBuilder.append(" ");
            // stringBuilder.append(str);
            stringBuilder.append(" \n");
            Log.d("Maing", "---------------------" + "exec: " + stringBuilder.toString());
            dataOutputStream.writeBytes(stringBuilder.toString());
            dataOutputStream.flush();
        } catch (Exception e) {
            StringBuilder stringBuilder2 = new StringBuilder();
            stringBuilder2.append("eeeeeeeee\n:");
            stringBuilder2.append(e.getMessage());
            Log.d("Maing", stringBuilder2.toString());
        }
    }

    public native int get_banner(byte[] data);

    public native byte[] get_cap(int quality);

    public native byte[] get_cap_no_yuv(int quality);

    public native int init_cap(int realInfo_width, int realInfo_height, int desiredInfo_width, int desiredInfo_height,
            int desiredInfo_orientation);

    public native int release_cap();

    public native int init_touch();

    public native void set_touch(byte[] sz);

    public native byte[] get_touch_limits();

    public native byte[] get_screen(int quality);

    public native int set_rotation(int realInfo_width, int realInfo_height, int desiredInfo_width,
            int desiredInfo_height, int desiredInfo_orientation);

    public native int set_quality(int quality);

    public native void enable_debug_info(boolean enable);

    public native void enable_touch_debug_info(boolean enable);

    public native byte[] get_cap_null(int quality);

    public native int reset_touch();

    public native int free_touch();

    public native byte[] get_screen(int realInfo_width, int realInfo_height, int desiredInfo_width,
            int desiredInfo_height, int desiredInfo_orientation, int quality);
}